﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LongGi.WatchFilesChangeWinserver
{
    using System;
    using System.IO;

    public class LogCleaner
    {
        public static void CleanLogsIfExceedsSize(string logsFolderPath, long maxSizeInBytes = 10 * 1024 * 1024)
        {
            try
            {
                // 检查文件夹是否存在
                if (!Directory.Exists(logsFolderPath))
                {
                    Console.WriteLine($"日志文件夹不存在: {logsFolderPath}");
                    return;
                }

                // 计算文件夹大小
                long folderSize = GetFolderSize(logsFolderPath);
                Console.WriteLine($"日志文件夹当前大小: {folderSize / 1024.0 / 1024.0:F2} MB");

                // 检查是否超过指定大小
                if (folderSize > maxSizeInBytes)
                {
                    Console.WriteLine($"日志文件夹大小超过限制 ({maxSizeInBytes / 1024 / 1024}MB)，开始清理...");

                    // 清理文件夹中的所有文件
                    CleanFolder(logsFolderPath);
                    Console.WriteLine("日志文件夹清理完成");
                }
                else
                {
                    Console.WriteLine("日志文件夹大小未超过限制，无需清理");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清理日志时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 计算文件夹大小
        /// </summary>
        private static long GetFolderSize(string folderPath)
        {
            long size = 0;

            // 获取所有文件并计算总大小
            var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                try
                {
                    var fileInfo = new FileInfo(file);
                    size += fileInfo.Length;
                }
                catch (FileNotFoundException)
                {
                    // 文件可能已被删除，忽略
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine($"无法访问文件: {file}");
                }
            }

            return size;
        }

        /// <summary>
        /// 清理文件夹中的所有文件
        /// </summary>
        private static void CleanFolder(string folderPath)
        {
            try
            {
                // 删除所有文件
                var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    try
                    {
                        File.Delete(file);
                        Console.WriteLine($"已删除文件: {file}");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"删除文件失败 {file}: {ex.Message}");
                    }
                }

                // 可以选择删除空文件夹（可选）
                // DeleteEmptySubfolders(folderPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清理文件夹时发生错误: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 删除空子文件夹（可选功能）
        /// </summary>
        private static void DeleteEmptySubfolders(string folderPath)
        {
            try
            {
                var subfolders = Directory.GetDirectories(folderPath, "*", SearchOption.AllDirectories);
                foreach (var subfolder in subfolders)
                {
                    try
                    {
                        if (Directory.GetFiles(subfolder).Length == 0 &&
                            Directory.GetDirectories(subfolder).Length == 0)
                        {
                            Directory.Delete(subfolder);
                            Console.WriteLine($"已删除空文件夹: {subfolder}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"删除文件夹失败 {subfolder}: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除空文件夹时发生错误: {ex.Message}");
            }
        }
    }
}
